<?php

namespace app\controllers;

use Yii;
use app\models\Customer;
use app\models\CustomerSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\FeeItem;

/**
 * CustomerController implements the CRUD actions for Customer model.
 */
class CustomerController extends CController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Customer models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CustomerSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
		
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
	
    /**
     * Lists all Customer models.
     * @return mixed
     */
    public function actionList()
    {
    	return $this->render('list', [
    		'nsPersonList' => Customer::getListNSPerson()
    	]);
    }

    public function actionList1()
    {
        return $this->render('list1', [
            'nsPersonList' => Customer::getListNSPerson()
        ]);
    }

    public function actionGetlist()
    {
    	//$list = \app\models\Customer::find() ->asArray()->all();
    	
    	$query = new \yii\db\Query();
    	$query -> select('*') -> from('customer');

        if($_POST['type_search'] == 'basic')
        {
            if($_POST['cust_name'] != ""){
                $query -> where(['like','cust_name',$_POST['cust_name']]);
            }
        }
        else
        {
            $query -> where('cust_type=:cust_type and close_month=:close_month and ns_person=:ns_person and is_operating=:is_operating and inactive=:inactive');
            $query -> addParams([':cust_type' => $_POST['cust_type'], ':close_month' => $_POST['close_month'], ':ns_person' => $_POST['ns_person'], ':is_operating' => $_POST['is_operating'], ':inactive' => $_POST['inactive']]);
        }

    	$list = $query -> all();


    	\Yii::$app->response->format = 'json';
    	return $list;
    }
    
    /**
     * Displays a single Customer model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Customer model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Customer();

        if(Yii::$app->request->isPost){
            $model -> load(Yii::$app->request->post());
            $model -> cust_id = Customer::getLastID($model -> is_operating);
            $model = $this -> saveUploadFile($model);
            $model -> save();

            $model->refresh();
            Yii::$app->response->format = 'json';
            return [
                'message' => 'Success!!!',
            ];
        }
        else {
            return $this->renderAjax('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Customer model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
	
        Yii::info("VH: actionUpdate");

        if(Yii::$app -> request -> isPost){
            $model->load(Yii::$app->request->post());
        	$params = Yii::$app->request->bodyParams;
        	
        	FeeItem::deleteAll("cust_id=" . $model -> cust_id);
        	
        	for($i=1; $i < sizeof($params['FeeItem']['item']); $i++){
        		$feeItem = new FeeItem();
        		
        		$feeItem -> fee = $params['FeeItem']['fee'][$i];
        		$feeItem -> item = $params['FeeItem']['item'][$i];
        		$feeItem -> fee_month = $params['FeeItem']['fee_month'][$i];
        		$feeItem -> cust_id = $model -> cust_id;
        		$feeItem -> save();
        	}

            $model -> other_fee_amount = sizeof($params['FeeItem']['item']) - 1;

            $model = $this -> saveUploadFile($model);
            $model -> save();

        	return $this->redirect("/customer/list");
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Customer model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Customer model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Customer the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Customer::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function saveUploadFile($model){
        $declaration_form_file = \yii\web\UploadedFile::getInstanceByName('declaration_form');
        $notification_form_file = \yii\web\UploadedFile::getInstanceByName('notification_form');

        if($declaration_form_file != null){
            $fileName = $model -> cust_id . '_' . $declaration_form_file->name;
            $declaration_form_file -> saveAs('upload/customer/' . $fileName);
            $model -> declaration_form = $fileName;
        }

        if($notification_form_file != null){
            $fileName = $model -> cust_id . '_' . $notification_form_file->name;
            $notification_form_file -> saveAs('upload/customer/' . $fileName);
            $model -> notification_form = $fileName;
        }

        return $model;
    }
}
